var add_article = document.getElementsByClassName('add_article')[0]
var control_article = document.getElementsByClassName('control_article')[0]
var back = document.getElementsByClassName('back')[0]

var article = document.getElementsByClassName('article')[0]
var list = document.getElementsByClassName('list')[0]

var list_ul = document.getElementsByClassName('list_ul')[0]

var input_title = article.getElementsByClassName('input_title')[0]
var input_classify = article.getElementsByClassName('input_classify')[0]
var input_content = article.getElementsByClassName('input_content')[0]
var input_submit = article.getElementsByClassName('input_submit')[0]

input_submit.addEventListener('click', function() {
    var title = input_title.value
    var content = input_content.value
    var time = new Date().toLocaleString('china', { hour12: false })
    var classify = input_classify.value
    var count = 0
    myAjax('POST', '/admin/addArticle', { title: title, content: content, time: time, classify: classify, count: count }).then((result) => {
        alert(result)
        input_title.value = ''
        input_content.value = ''
        input_classify.value = ''
    })
    handle()
})
add_article.addEventListener('click', function() {
    add_article.className = 'add_article active'
    control_article.className = 'control_article'
    article.style.zIndex = 100
    list.style.zIndex = 0
})
control_article.addEventListener('click', function() {
    add_article.className = 'add_article'
    control_article.className = 'control_article active'
    list.style.zIndex = 100
    article.style.zIndex = 0
})
back.addEventListener('click', function () {
    location.href = 'home.html'
})

function renderGetAllArticleData(result) {
    var arr = JSON.parse(result)
    arr.forEach(item => {
        var li = document.createElement('li')
        li.className = 'list_item'
        var p = document.createElement('p')
        var button = document.createElement('button')
        button.className = 'item_delete'
        button.setAttribute('data-id', item._id)
        button.addEventListener('click', function() {
            var id = this.getAttribute('data-id')
            myAjax('POST', '/admin/deleteArticle', { id: id }).then((result) => {
                alert(result)
                list_ul.innerHTML = ''
                handle()
            })
        })
        p.innerHTML = item.title
        button.innerHTML = '删除'
        li.appendChild(p)
        li.appendChild(button)
        list_ul.appendChild(li)
    });
}

async function handle() {
    var getAllArticleData = await myAjax('GET', '/admin/getAllArticle', null)
    renderGetAllArticleData(getAllArticleData)
}
handle()